import COS from 'cos-wx-sdk-v5';
import {query} from "@/_framework/services/Data";
import Taro from "@tarojs/taro";
import {failToast, getImageInfo} from "@/_framework/services/Taro";

const cos = new COS({
    getAuthorization: async (_, callback) => {
        const {sessionToken, tmpSecretId, tmpSecretKey, startTime, expiredTime} = await query(
            'system/cos/getCredential'
        );
        callback({
            TmpSecretId: tmpSecretId,
            TmpSecretKey: tmpSecretKey,
            XCosSecurityToken: sessionToken,
            StartTime: startTime,
            ExpiredTime: expiredTime
        });
    }
});

async function postObject(filename, filePath) {
    const {bucket, region} = await query(
        'system/cos/getBucket'
    );
    return new Promise(reslove => {
        cos.postObject(
            {
                Bucket: bucket,
                Region: region,
                Key: new Date().getTime() + '-' + filename,
                FilePath: filePath,
                onProgress: ({speed}) => {
                    if (speed === 0) {
                    }
                }
            },
            (err, data) => reslove({err, data})
        );
    });
}

// 上传单个图片
export const uploadImage = async filePath => {

    const fileInfo = await Taro.getFileInfo({filePath});
    const fileSizeInBytes = fileInfo.size;
    const fileSizeInMB = fileSizeInBytes / (1024 * 1024);

    // 检查文件大小是否超过 3MB
    if (fileSizeInMB > 3) {
        failToast('文件大小不能超过 3MB');
        return {};
    }

    const filename = filePath.substr(filePath.lastIndexOf('/') + 1);
    const {err, data} = await postObject(filename, filePath);
    if (err) {
        console.log('postObject error : ', err)
        return {};
    }
    const {height, width, type} = await getImageInfo(filePath)

    return {url: 'https://' + data.Location, size: fileSizeInBytes, height, width, type}
}
//批量上传图片
export const uploadImages = async filePaths => {
    let list = []
    for (const filePath of filePaths) {
        const res = await uploadImage(filePath.url)
        if (!res.url) continue
        list.push(res)
    }

    return list;
}

export const chooseImage = async (count = 1) => {
    const {tempFiles} = await Taro.chooseImage({
        count,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
    });
    const images = tempFiles.map(({path, type, originalFileObj}) => ({
        url: path,
        type,
        name: originalFileObj?.name
    }))
    return images;

}